package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.client.api.scene.query.IQuerySceneAccessProdInstService;
import com.iwhalecloud.bss.kite.client.dto.inst.ProdInstDTO;
import com.iwhalecloud.bss.kite.client.vo.scene.ModuleVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.api.biz.IBizService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ReceiptInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ResourceCheck;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.ResourceCheckInfoVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.SceneNewOfferSeneVO;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.manager.scene.service.QuerySceneInstService;
import com.iwhalecloud.bss.kite.web.service.accept.bo.AcceptContext;
import com.iwhalecloud.bss.kite.web.service.accept.bo.SceneModule;
import com.iwhalecloud.bss.kite.web.service.accept.handler.module.AbstractModuleHandler;

import com.ztesoft.bss.common.util.SpringUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author yangwj
 */
@Service
public class GoodsServiceInfoModuleHandler extends AbstractModuleHandler {
    /**
     * INSERT INTO `cfg1`.`inf_service` (`svc_code`, `svc_name`, `class_name`, `is_sync`, `svc_desc`, `version`, `state`, `create_staff_id`, `create_date`, `status_date`, `owner`, `consumer_bean_id`, `type`, `param_types`) VALUES ('local-cucc-getBizServiceList', '', 'https://10.124.195.138/api/v2/query/orders/getServiceList', 'T', '受理单下载', '1.0', '00A', '0027008265', NULL, '2017-07-24 00:00:00', 'order', '', NULL, NULL);
     * INSERT INTO `cfg1`.`inf_service` (`svc_code`, `svc_name`, `class_name`, `is_sync`, `svc_desc`, `version`, `state`, `create_staff_id`, `create_date`, `status_date`, `owner`, `consumer_bean_id`, `type`, `param_types`) VALUES ('local-cucc-getOrderProgressInfo', '', 'https://10.124.195.138/api/v2/query/orderFollow', 'T', '进度查询', '1.0', '00A', '0027008265', NULL, '2017-07-24 00:00:00', 'order', '', NULL, NULL);
     * INSERT INTO `cfg1`.`kite_module` (`module_name`, `module_type`, `layout_page`, `js_path`, `handler_class`, `status_cd`, `is_show`, `order_id`) VALUES ('核查转定', '1', NULL, NULL, 'com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.module.GoodsServiceInfoModuleHandler', NULL, 'T', '1');
     * INSERT INTO `cfg1`.`kite_template_module_rel` (`template_id`, `module_id`, `create_date`, `update_date`, `operator_staff`, `status_cd`, `order_id`) VALUES ('1', '95', NULL, NULL, NULL, '1000', '1');
     */

    @Autowired
    private QuerySceneInstService querySceneInstService;

    @Autowired
    private IQuerySceneAccessProdInstService querySceneAccessProdInstService;

    @Autowired
    private IBizService bizService;

    @Override
    public List<? extends ModuleVO> execute(AcceptContext context, SceneModule sceneModule) {
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneVo().getSceneInstId());

        List<ResourceCheck> goodsInfoList = this.getGoodsInfo(context, sceneModule);
        if (KiteStringUtils.equals(kiteSceneInst.getServiceOfferId(), "1013")) {
            goodsInfoList = this.getResourceCheck(context, sceneModule);
        }

        if (KiteListUtils.isEmpty(goodsInfoList)) {
            return Lists.newArrayList();
        }
        ResourceCheckInfoVO resourceCheckInfo = new ResourceCheckInfoVO();
        resourceCheckInfo.setResourceCheckList(goodsInfoList);
        ((SceneNewOfferSeneVO) context.getSceneVo()).setResourceCheckInfo(resourceCheckInfo);
        return Collections.singletonList(resourceCheckInfo);
    }

    private List<ResourceCheck> getGoodsInfo(AcceptContext context, SceneModule sceneModule) {
        //获取orderId
        String orderId = this.querySceneInstService
            .getExtParameterValue(context.getSceneVo().getSceneInstId(), "outOrderId");
        if (KiteStringUtils.isEmpty(orderId)) {
            return Lists.newArrayList();
        }
        Map<String, Object> dataMap = this.bizService.getBizServiceList(orderId);

        JSONObject dataJson = JSONObject.parseObject(JSONObject.toJSONString(dataMap));

        if (KiteObjectUtils.isEmpty(dataJson)) {
            return Lists.newArrayList();
        }

        List<ResourceCheck> goodsInfoList = new ArrayList<>();
        //主商品
        ResourceCheck mainGoodsInfo = new ResourceCheck();
        mainGoodsInfo.setOrderCode(JSONPath.eval(dataJson, "$.mainServiceList.orderId").toString());
        //业务号码
        mainGoodsInfo.setBizNum((String) JSONPath.eval(dataJson, "$.mainServiceList.serialNumber"));
        mainGoodsInfo.setGoodsName((String) JSONPath.eval(dataJson, "$.mainServiceList.goods[0].name"));
        JSONArray attrArray = (JSONArray) JSONPath.eval(dataJson, "$.mainServiceList.goods[0].attrs");
        //attrs查找属性
        //带宽
        mainGoodsInfo.setBandWidth(Optional.ofNullable(this.getAttrValue(attrArray, "2_0000001")).orElse(""));
        //发端城市
        mainGoodsInfo.setSenderCity(Optional.ofNullable(this.getAttrValue(attrArray, "200002079")).orElse(""));
        //收端城市
        mainGoodsInfo.setReceiverCity(Optional.ofNullable(this.getAttrValue(attrArray, "200002107")).orElse(""));
        //租用范围
        mainGoodsInfo.setRentRange(Optional.ofNullable(this.getAttrValue(attrArray, "200002042")).orElse(""));
        //计费模式
        mainGoodsInfo.setChargeMethod(Optional.ofNullable(this.getAttrValue(attrArray, "200002037")).orElse(""));

        //回执信息
        List<ReceiptInfoVO> mainReceiptInfos = new ArrayList<>();
        JSONArray array = (JSONArray) JSONPath.eval(dataJson, "$.mainServiceList.flowData");
        this.getReceiptInfoVO(array, mainReceiptInfos);
        mainGoodsInfo.setReceiptInfos(mainReceiptInfos);
        goodsInfoList.add(mainGoodsInfo);

        //子商品
        JSONArray subServiceArray = dataJson.getJSONArray("subServiceList");
        Iterator it = subServiceArray.iterator();
        while (it.hasNext()) {
            JSONObject subGoodsJson = (JSONObject) it.next();
            ResourceCheck subGoodsInfo = new ResourceCheck();
            //业务号码
            subGoodsInfo.setBizNum((String) JSONPath.eval(subGoodsJson, "$.serialNumber"));
            subGoodsInfo.setGoodsCatagory((String) JSONPath.eval(subGoodsJson, "$.goodsCatagoriesName"));
            subGoodsInfo.setGoodsName((String) JSONPath.eval(subGoodsJson, "$.goods[0].name"));
            //订单环节
            subGoodsInfo.setOrderNode((String) JSONPath.eval(subGoodsJson, "$.flowNodeName"));
            //资源情况
            subGoodsInfo.setResourceStatus((String) JSONPath.eval(subGoodsJson, "$.statusName"));

            //回执信息
            List<ReceiptInfoVO> subReceiptInfos = new ArrayList<>();
            JSONArray subArray = (JSONArray) JSONPath.eval(subGoodsJson, "$.flowData");
            if (!KiteObjectUtils.isEmpty(subArray)) {
                this.getReceiptInfoVO(subArray, subReceiptInfos);
            }
            subGoodsInfo.setReceiptInfos(subReceiptInfos);
            goodsInfoList.add(subGoodsInfo);
        }
        //将数据存入SceneNewOfferSeneVO对象
        return goodsInfoList;
    }

    /**
     * 获取ReceiptInfoVO对象
     *
     * @param array
     * @param receiptInfos
     */
    private void getReceiptInfoVO(JSONArray array, List<ReceiptInfoVO> receiptInfos) {
        Iterator its = array.iterator();
        while (its.hasNext()) {
            ReceiptInfoVO receiptInfoVO = new ReceiptInfoVO();
            JSONObject flowData = (JSONObject) its.next();
            //组件暂时不需要展示属性
/*            List<FlowValueInfoVO> flowValueInfos = new ArrayList<>();
            String flowValueStr = flowData.getString("flowValue");
            JSONArray flowValueArray = JSONArray.parseArray(flowValueStr);
            flowValueArray.stream().forEach(flowValue -> flowValueInfos.add(JSONObject.toJavaObject((JSON) flowValue,FlowValueInfoVO.class)));
            receiptInfoVO.setFlowValues(flowValueInfos);*/

            receiptInfoVO.setFlowKey(flowData.getString("flowKey"));
            receiptInfoVO.setTaskId(flowData.getString("taskId"));
            receiptInfoVO.setOrderId(flowData.getString("orderId"));
            receiptInfoVO.setFlowDataId(flowData.getString("flowDataId"));

            receiptInfos.add(receiptInfoVO);
        }
    }

    /**
     * 根据code获取flowData中的值
     *
     * @param receiptInfoVO
     * @param flowData
     * @param code
     */
    private void getReceiptInfo(ReceiptInfoVO receiptInfoVO, JSONObject flowData, String code) {
        if (flowData.getString(code) == null) {
            receiptInfoVO.setTaskId("");
        }
        receiptInfoVO.setTaskId(flowData.getString(code));
    }

    /**
     * 获取attr属性
     *
     * @param attrArray
     * @param code
     * @return
     */
    private String getAttrValue(JSONArray attrArray, String code) {
        JSONObject attrJson = (JSONObject) attrArray.stream()
            .filter(attr -> attr != null && code.equals(((JSONObject) attr).getString("code"))).distinct().findAny()
            .orElse(null);
        return attrJson == null ? null : attrJson.getString("value");
    }

    private List<ResourceCheck> getResourceCheck(AcceptContext context, SceneModule sceneModule) {
        String sceneInstId = context.getSceneVo().getSceneInstId();
        String custId = context.getAcceptRequest().getCustId();
        Map<String, Object> orderInfo = querySceneInstService.getExtParameterValue(sceneInstId, "orderInfoMap");
        if (KiteMapUtils.isEmpty(orderInfo)) {
            return Collections.emptyList();
        }
        Map<String, Object> orderMap = KiteMapUtils.getValue(orderInfo, "order");
        List<Map<String, Object>> userList = (List<Map<String, Object>>) Optional.ofNullable(orderInfo.get("users"))
            .orElse(Collections.EMPTY_LIST);
        List<Map<String, Object>> paymentsList = (List<Map<String, Object>>) Optional
            .ofNullable(orderInfo.get("payments")).orElse(Collections.EMPTY_LIST);

        List<ResourceCheck> goodsInfoList = new ArrayList<>();
        //主商品
        ResourceCheck mainGoodsInfo = new ResourceCheck();
        // 订单编码
        mainGoodsInfo.setOrderCode(KiteMapUtils.getString(orderMap, "orderId"));
        // 商品名称
        mainGoodsInfo.setGoodsName(KiteMapUtils.getString(orderMap, "goodsNames"));
        IUnicomRegionService unicomRegionService = SpringUtil.getBean(IUnicomRegionService.class);
        // 发端城市
        mainGoodsInfo.setSenderCity(
            Optional.ofNullable(unicomRegionService.getRegion(KiteMapUtils.getString(orderMap, "sendCity")))
                .map(UnicomRegion::getRegionName).orElse(""));
        // 收端城市
        mainGoodsInfo.setReceiverCity(
            Optional.ofNullable(unicomRegionService.getRegion(KiteMapUtils.getString(orderMap, "receiveCity")))
                .map(UnicomRegion::getRegionName).orElse(""));
        // 订单环节
        mainGoodsInfo.setOrderNode(KiteMapUtils.getString(orderMap, "flowNodeName"));
        // 资源情况
        mainGoodsInfo.setResourceStatus(KiteMapUtils.getString(orderMap, "statusName"));
        // 商品分类
        mainGoodsInfo.setGoodsCatagory(KiteMapUtils.getString(orderMap, "goodsCatagoriesName"));
        // 商品分类
        mainGoodsInfo.setChargeMethod(Optional.ofNullable(paymentsList.get(0).get("payType")).orElse("").toString());
        List<ProdInstDTO> prodInstList = querySceneAccessProdInstService.listEffProdInsts(sceneInstId, custId)
            .getResultObject();
        prodInstList = prodInstList.stream()
            .filter((prodInst) -> KeyConsts.PROD_FUNC_TYPE_101.equals(prodInst.getProdFuncType()))
            .collect(Collectors.toList());
        // 带宽
        mainGoodsInfo.setBandWidth(Optional
            .ofNullable(querySceneInstService.getProdInstAttr(custId, prodInstList.get(0).getProdInstId(), "2_0000061"))
            .orElse(new KiteAttr()).getValueDesc());
        // 计费模式
        mainGoodsInfo.setChargeMethod(Optional
            .ofNullable(querySceneInstService.getProdInstAttr(custId, prodInstList.get(0).getProdInstId(), "200003092"))
            .orElse(new KiteAttr()).getValueDesc());
        // 业务号码
        if (KiteListUtils.isNotEmpty(userList)) {
            mainGoodsInfo.setBizNum(Optional.ofNullable(userList.get(0).get("serialNumber")).orElse("").toString());
        }

        List<ReceiptInfoVO> subReceiptInfoList = new ArrayList<ReceiptInfoVO>();
        ReceiptInfoVO subReceiptInfoVO = new ReceiptInfoVO();
        subReceiptInfoVO.setFlowDataId(KiteMapUtils.getString(orderMap, "flowInstanceId"));
        subReceiptInfoVO.setFlowKey(KiteMapUtils.getString(orderMap, "flowNodeId"));
        subReceiptInfoVO.setOrderId(KiteMapUtils.getString(orderMap, "orderId"));
        subReceiptInfoVO.setTaskId(KiteMapUtils.getString(orderMap, "taskId"));
        mainGoodsInfo.setReceiptInfos(subReceiptInfoList);
        goodsInfoList.add(mainGoodsInfo);

        //        taskId = KiteMapUtils.getString(orderMap, "taskId");
        //        IOrderService orderService = SpringUtil.getBean(IOrderService.class);
        //        Map<String, Object> orderInfo = orderService.getWorkOrderInfo(orderId, flowId, taskId);

        return goodsInfoList;
    }
}
